<!--
 * @Author: early-autumn
 * @Date: 2020-05-08 19:39:54
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 15:40:06
 -->
<template>
  <el-dialog
    :title="form.id ? '修改患者' : '新增患者'"
    :visible="value"
    width="1080px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" label-width="110px" :model="form" :rules="rules">
      <el-tabs>
        <el-tab-pane label="必填信息">
          <el-row>
            <el-col :span="8">
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  :style="{ width: '100%' }"
                  :editable="true"
                  :clearable="false"
                  placeholder="选择生日"
                  @input="handleBirthdayToAge"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input
                  v-model="form.age"
                  placeholder="请输入年龄"
                  @input="handleAgeToBirthday"
                />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio
                    v-for="option in sexOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="病种" prop="department">
                <el-select
                  v-model="form.department"
                  :style="{ width: '100%' }"
                  placeholder="请选择病种"
                >
                  <el-option
                    v-for="option in entityAllOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="初诊TC" prop="firstTc">
                <el-select
                  v-model="form.firstTc"
                  :style="{ width: '100%' }"
                  placeholder="请选择初诊TC"
                >
                  <el-option
                    v-for="option in tcOptions"
                    :key="option.userName"
                    :label="option.userName"
                    :value="option.userName"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="建档人" prop="filingPerson">
                <el-input
                  v-model="form.filingPerson"
                  disabled
                  placeholder="请输入建档人"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号" prop="phoneNumber">
                <el-input
                  v-model="form.phoneNumber"
                  :disabled="!!market || !!patient"
                >
                  <template slot="append">
                    <el-select
                      v-model="form.phoneOwnership"
                      :style="{ width: '100px' }"
                      placeholder="使用人"
                    >
                      <el-option
                        v-for="option in phoneOwnershipOptions"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="手机号2" prop="phoneNumber2">
                <el-input v-model="form.phoneNumber2">
                  <template slot="append">
                    <el-select
                      v-model="form.phoneOwnership2"
                      :style="{ width: '100px' }"
                      placeholder="使用人"
                    >
                      <el-option
                        v-for="option in phoneOwnershipOptions"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="渠道" prop="channelFirst">
                <el-cascader
                  v-model="channel"
                  :style="{ width: '100%' }"
                  placeholder="请选择渠道"
                  :disabled="true"
                  :options="channelOptions"
                  @change="handleChannelChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="媒介" prop="channelFirst">
                <el-cascader
                  v-model="medium"
                  :style="{ width: '100%' }"
                  placeholder="请选择媒介"
                  :options="channelOptions"
                  @change="handleMediumChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="推荐人" prop="referrer">
                <el-form
                  v-if="!form.referrerId"
                  ref="searchReferenceForm"
                  :model="searchReference.form"
                  :rules="searchReference.rules"
                  inline
                >
                  <el-form-item prop="keyword" :style="{ width: '100%' }">
                    <el-input
                      v-model="searchReference.form.keyword"
                      placeholder="推荐人手机号"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="handleSearchReferenceSubmit"
                      >
                        搜索
                      </el-button>
                    </el-input>
                  </el-form-item>
                </el-form>
                <el-tag
                  v-else
                  effect="dark"
                  closable
                  @close="handleSearchReferenceClose"
                >
                  {{ form.referrerName }} {{ form.referrerPhoneNumber }}
                </el-tag>
              </el-form-item>
              <el-form-item
                v-if="form.referrerId"
                label="推荐人关系"
                prop="referrerRelation"
              >
                <el-select
                  v-model="form.referrerRelation"
                  :style="{ width: '100%' }"
                  placeholder="请选择推荐人关系"
                >
                  <el-option
                    v-for="option in referrerRelationshipOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户状态" prop="personStatus">
                <el-input
                  v-model="form.personStatus"
                  disabled
                  placeholder="请输入客户状态"
                ></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="province">
                <el-cascader
                  v-model="location"
                  :style="{ width: '100%' }"
                  placeholder="请选择地址"
                  :options="locationOptions"
                  @change="handleLocationChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="详细地址" prop="addressDetailed">
                <el-input
                  v-model="form.addressDetailed"
                  placeholder="请输入详细地址"
                ></el-input>
              </el-form-item>
              <el-form-item label="黄页编号" prop="yellowCode">
                <el-input
                  v-model="form.yellowCode"
                  placeholder="请输入黄页编号"
                ></el-input>
              </el-form-item>
              <el-form-item label="职业" prop="profession">
                <el-select
                  v-model="form.profession"
                  :style="{ width: '100%' }"
                  placeholder="请选择职业"
                >
                  <el-option
                    v-for="option in professionalOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="输入卡号" prop="cardNumber">
                <el-input v-model="form.cardNumber" placeholder="请输入卡号" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="选填选项">
          <el-row>
            <el-col :span="8">
              <el-form-item label="经济能力" prop="economics">
                <el-select
                  v-model="form.economics"
                  :style="{ width: '100%' }"
                  placeholder="请选择经济能力"
                >
                  <el-option
                    v-for="option in economicAbilityOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="消费习惯" prop="consumptionCustom">
                <el-select
                  v-model="form.consumptionCustom"
                  :style="{ width: '100%' }"
                  placeholder="请选择消费习惯"
                >
                  <el-option
                    v-for="option in spendingHabitsOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="qq号" prop="qqNumber">
                <el-input v-model="form.qqNumber" placeholder="请输入qq号" />
              </el-form-item>
              <el-form-item label="微信号" prop="wechatNumber">
                <el-input
                  v-model="form.wechatNumber"
                  placeholder="请输入微信号"
                />
              </el-form-item>
              <el-form-item label="Email" prop="email">
                <el-input v-model="form.email" placeholder="请输入Email" />
              </el-form-item>
              <el-form-item label="邮编" prop="postcode">
                <el-input v-model="form.postcode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻状况" prop="maritalStatus">
                <el-radio-group v-model="form.maritalStatus">
                  <el-radio
                    v-for="option in maritalStatusOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="有无小孩" prop="haveChild">
                <el-radio-group v-model="form.haveChild">
                  <el-radio
                    v-for="option in haveChildOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="性格" prop="personality">
                <el-select
                  v-model="form.personality"
                  :style="{ width: '100%' }"
                  placeholder="请选择性格"
                >
                  <el-option
                    v-for="option in characterOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </div>

    <search-reference
      v-model="searchReference.visible"
      :keyword="searchReference.form.keyword"
      @ok="handleSearchReferenceOk"
    ></search-reference>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import dayjs from 'dayjs'
import { CodeToText, TextToCode, regionData } from 'element-china-area-data'
import { addPerson, updatePerson } from '@/api/services/person'
import { listStaff } from '@/api/services/common'
import { listChannel } from '@/api/erp/channel'
import { listToTreeOptions } from '@/utils/utils'
import {
  characterOptions,
  customerStatusOptions,
  economicAbilityOptions,
  entityAllOptions,
  haveChildOptions,
  maritalStatusOptions,
  phoneOwnershipOptions,
  professionalOptions,
  referrerRelationshipOptions,
  sexOptions,
  spendingHabitsOptions,
  temporaryPatientOptions,
} from '@/utils/options'
import { sexEnum } from '@/utils/enums'
import { rulesPhone } from '@/utils/regexps'
import SearchReference from '@/views/shop/components/SearchReference/index'
import { getReservation } from '@/api/erp/reservation'

const DEFAULT_FORM = {
  id: undefined,
  marketReservationId: undefined,
  caseNumber: undefined,
  name: undefined,
  sex: undefined,
  age: undefined,
  phoneNumber: '',
  phoneOwnership: undefined,
  phoneNumber2: '',
  phoneOwnership2: undefined,
  department: undefined,
  wechatNumber: undefined,
  qqNumber: undefined,
  email: undefined,
  birthday: undefined,
  arriveClinic: undefined,
  branch: undefined,
  postcode: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  addressDetailed: undefined,
  profession: undefined,
  haveChild: undefined,
  maritalStatus: undefined,
  personality: undefined,
  consumptionCustom: undefined,
  economics: undefined,
  channelFirst: undefined,
  channelSecond: undefined,
  channelThird: undefined,
  mediumFirst: undefined,
  mediumSecond: undefined,
  mediumThird: undefined,
  personStatus: '新客首次',
  scanStatus: undefined,
  firstOnClinicTime: undefined,
  overMoney: undefined,
  arrearage: undefined,
  billingState: undefined,
  doctor: undefined,
  firstDiagnoseTime: undefined,
  firstTc: undefined,
  yellowCode: undefined,
  networkCounselor: undefined,
  idCard: undefined,
  cardNumber: undefined,
  filingPerson: undefined,
  referrerId: undefined,
  referrerName: undefined,
  referrerPhoneNumber: undefined,
  referrerRelation: undefined,
  filingTime: undefined,
  remarks: undefined,
  createBy: undefined,
}

export default {
  name: 'PatientEditorPanel',
  components: {
    SearchReference,
  },
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    market: {
      type: Object,
      default: undefined,
      required: false,
    },
    patient: {
      type: Object,
      default: undefined,
      required: false,
    },
    phoneNumber: {
      type: String,
      default: undefined,
      required: false,
    },
  },
  data() {
    return {
      loading: false,
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
        department: [
          { required: true, message: '病种不能为空', trigger: 'blur' },
        ],
        firstTc: [{ required: true, message: 'TC不能为空', trigger: 'blur' }],
        birthday: [
          { required: true, message: '生日不能为空', trigger: 'blur' },
        ],
        phoneNumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          // { pattern: phoneNumberRegexp, message: '手机号格式不正确', trigger: 'blur' },
        ],
        phoneOwnership: [
          { required: true, message: '电话所属关系', trigger: 'blur' },
        ],
        province: [
          { required: true, message: '地址不能为空', trigger: 'blur' },
        ],
        channelFirst: [
          { required: true, message: '渠道不能为空', trigger: 'blur' },
        ],
        mediumFirst: [
          { required: true, message: '媒介不能为空', trigger: 'blur' },
        ],
        personStatus: [
          { required: true, message: '客户状态不能为空', trigger: 'blur' },
        ],
        yellowCode: [
          { required: true, message: '黄页编号不能为空', trigger: 'blur' },
        ],
        filingPerson: [
          { required: true, message: '建档人不能为空', trigger: 'blur' },
        ],
      },
      // tc 选项
      tcOptions: [],
      // 渠道选项
      channelOptions: [],
      // 渠道联动
      channel: [],
      // 媒介联动
      medium: [],
      // 地址
      location: [],

      searchReference: {
        visible: false,
        form: {
          keyword: undefined,
        },
        rules: {
          keyword: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            {
              pattern: rulesPhone,
              message: '手机号格式不正确',
              trigger: 'blur',
            },
          ],
        },
      },
    }
  },
  computed: {
    ...mapState({
      clinicName: (state) => state.clinic.clinicName,
      clinicId: (state) => state.clinic.clinicId,
      userName: (state) => state.user.name,
    }),
    locationOptions() {
      return regionData
    },
    sexOptions() {
      return sexOptions
    },
    sexEnum() {
      return sexEnum
    },
    phoneOwnershipOptions() {
      return phoneOwnershipOptions
    },
    maritalStatusOptions() {
      return maritalStatusOptions
    },
    haveChildOptions() {
      return haveChildOptions
    },
    customerStatusOptions() {
      return customerStatusOptions
    },
    temporaryPatientOptions() {
      return temporaryPatientOptions
    },
    economicAbilityOptions() {
      return economicAbilityOptions
    },
    spendingHabitsOptions() {
      return spendingHabitsOptions
    },
    characterOptions() {
      return characterOptions
    },
    professionalOptions() {
      return professionalOptions
    },
    referrerRelationshipOptions() {
      return referrerRelationshipOptions
    },
    entityAllOptions() {
      return entityAllOptions
    },
  },
  watch: {
    value(newVal) {
      if (newVal) {
        this.init()
        if (this.phoneNumber) {
          this.form.department = '成人-其他'
        }
      } else {
        this.channel = []
        this.location = []
        this.$refs.form.resetFields()
      }
    },
  },
  mounted() {
    this.getListStaff()
    this.getChannelOptions()
  },
  methods: {
    /**
     * 初始化表单数据
     */
    async init() {
      this.form = { ...DEFAULT_FORM }
      if (this.patient) {
        await this.initPatient(this.patient)
      } else if (this.market) {
        this.initMarket(this.market)
      } else {
        this.initCreate()
      }
      if (!this.form.province) {
        this.form.province = '湖北省'
        this.form.city = '恩施土家族苗族自治州'
        this.form.district = '咸丰县'
        this.location = [
          TextToCode['湖北省'].code,
          TextToCode['湖北省']['恩施土家族苗族自治州'].code,
          TextToCode['湖北省']['恩施土家族苗族自治州']['咸丰县'].code,
        ]
      }
      const { channelFirst, channelSecond, channelThird } = this.form
      const initChannel =
        !channelFirst || channelFirst.channelFirst === '直接上门'
          ? ['直接上门', '直接上门', '直接上门']
          : [channelFirst, channelSecond, channelThird]

      this.channel = initChannel
      this.medium = initChannel
      this.handleChannelChange(initChannel)
      this.handleMediumChange(initChannel)
      this.form.createBy = this.form.createBy || this.userName
    },
    initCreate() {
      this.form = {
        ...this.form,
        phoneNumber: rulesPhone.test(this.phoneNumber) ? this.phoneNumber : '',
        name: rulesPhone.test(this.phoneNumber) ? '' : this.phoneNumber,
        phoneOwnership: 0,
        filingPerson: this.userName,
        personStatus: '新客首次',
      }
    },
    async initPatient(patient) {
      const { marketReservationId, age, filingPerson, personStatus } = patient
      this.form = {
        ...this.form,
        ...patient,
        filingPerson: filingPerson || this.userName,
        personStatus: personStatus || '新客首次',
      }
      if (marketReservationId) {
        const { data } = await getReservation(marketReservationId)
        this.initMarket(data)
      }
      this.handleAgeToBirthday(age)
    },
    initMarket(market) {
      const { id } = this.form
      const {
        id: marketReservationId,
        age,
        visitDisease,
        filingPerson,
        personStatus,
      } = market
      this.form = {
        ...this.form,
        ...market,
        personStatus: personStatus || '新客首次',
        marketReservationId,
        department: visitDisease,
        filingPerson: filingPerson || this.userName,
        id,
      }
      this.handleAgeToBirthday(age)
    },
    /**
     * 获取TC列表
     */
    async getListStaff() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcOptions = data
    },
    /**
     * 获取联级渠道
     */
    async getChannelOptions() {
      const { rows } = await listChannel({
        pageNum: 1,
        pageSize: 10000000,
      })
      const options = listToTreeOptions(rows, ({ pid, id, name }) => ({
        parentId: pid,
        id,
        label: name,
        value: name,
      }))
      options.unshift({
        label: '直接上门',
        value: '直接上门',
        children: [
          {
            label: '直接上门',
            value: '直接上门',
            children: [{ label: '直接上门', value: '直接上门' }],
          },
        ],
      })

      this.channelOptions = options
    },
    /**
     * 选择渠道
     */
    handleChannelChange(e) {
      ;[
        this.form.channelFirst,
        this.form.channelSecond,
        this.form.channelThird,
      ] = e
    },
    /**
     * 选择媒介
     */
    handleMediumChange(e) {
      ;[
        this.form.mediumFirst,
        this.form.mediumSecond,
        this.form.mediumThird,
      ] = e
    },
    /**
     * 选择地址
     */
    handleLocationChange(e) {
      const [province, city, district] = e

      this.form.province = CodeToText[province]
      this.form.city = CodeToText[city]
      this.form.district = CodeToText[district]
    },

    /**
     * 提交
     */
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        try {
          if (!valid) {
            return
          }
          this.loading = true
          const { age, birthday } = this.form
          const formData = {
            ...this.form,
            age: +age,
            birthday: dayjs(birthday).format('YYYY-MM-DD'),
            isTemporary: 1,
            arriveClinic: this.clinicName,
          }
          let id
          if (this.form.id) {
            id = this.form.id
            await updatePerson({
              ...formData,
              phoneNumber: undefined,
              phoneOwnership: undefined,
            })
          } else {
            const { data } = await addPerson(formData)
            id = data
          }
          this.msgSuccess(this.form.id ? '修改成功' : '新增成功')
          this.handleClose()
          this.$emit('submit', { ...formData, id })
        } finally {
          this.loading = false
        }
      })
    },
    /**
     * 取消
     */
    handleClose() {
      this.$emit('close', false)
    },
    /**
     * 年龄转生日
     */
    handleAgeToBirthday(age) {
      const year = dayjs().subtract(age, 'year').format('YYYY')
      const md = dayjs(this.form.birthday).format('MM-DD')

      this.form.birthday = dayjs(`${year}-${md}`)
    },
    /**
     * 生日转年龄
     */
    handleBirthdayToAge(birthday) {
      this.form.age = dayjs().diff(dayjs(birthday), 'year')
    },

    handleSearchReferenceSubmit() {
      this.$refs.searchReferenceForm.validate((valid) => {
        if (!valid) {
          return
        }

        this.searchReference.visible = true
      })
    },

    handleSearchReferenceOk(e) {
      const { id, name, phoneNumber } = e

      this.form.referrerId = id
      this.form.referrerName = name
      this.form.referrerPhoneNumber = phoneNumber
    },

    handleSearchReferenceClose() {
      this.form.referrerId = undefined
      this.form.referrerName = undefined
      this.form.referrerPhoneNumber = undefined
      this.form.referrerRelation = undefined
    },
  },
}
</script>
